//
//  BookDetailViewController.m
//  ChangJiangPress
//
//  Created by 泉 汉水 on 11-12-1.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "BookDetailViewController.h"
#import "HubuAppDelegate.h"
#import "HubuViewController.h"
#import "CommonUtil.h"
#import "RegexKitLite.h"


@implementation BookDetailViewController
@synthesize bookId;
@synthesize bookFaceView;
@synthesize faceWaitingView;
@synthesize bookTitleAuthor;
@synthesize bookCategory;
@synthesize bookPressTime;
@synthesize bookPress;
@synthesize bookWords;
@synthesize bookLanguage;
@synthesize bookFocusLabel;
@synthesize starView;

@synthesize buyButton;

@synthesize currentButton;
@synthesize currentContent;
@synthesize waitingView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [bookId release];
    [bookItem release];
    [bookFaceView release];
    [faceWaitingView release];
    [bookTitleAuthor release];
    [bookCategory release];
    [bookPressTime release];
    [bookPress release];
    [bookWords release];
    [bookLanguage release];
    [bookFocusLabel release];
    [starView release];
    
    [buyButton release];
    
    [currentButton release];
    [currentContent release];
    [waitingView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [waitingView startAnimating];
    
    if(bookItem == nil) {
        bookItem = [[BookItem alloc] init];
    }
    
    DBUtil *db = [[DBUtil alloc] init];
    [db openDB];
    [db getBookDetailData:bookItem bookId:bookId];
    [db closeDB];
    [db release];
    
    bookTitleAuthor.text = [NSString stringWithFormat:@"[%@] %@" ,bookItem.bookAuthor, bookItem.bookName];
    if([bookItem bookSeries] != nil && ![[bookItem bookSeries] isEqualToString:@""]) {
        bookCategory.text = [NSString stringWithFormat:@"%@：%@", [bookItem bookCategory1], [bookItem bookSeries]];
    }else{
        bookCategory.text = [bookItem bookCategory1];
    }
    bookPressTime.text = bookItem.bookPressTime;
    bookPress.text = bookItem.bookPress;
    bookWords.text = bookItem.bookWords;
    bookLanguage.text = bookItem.bookLanguage;
    bookFocusLabel.text = [NSString stringWithFormat:@"%@ 次下载    %@ 次关注", 
                           [bookItem bookDownCount], [bookItem bookFocusCount]];
    starView.image = [UIImage imageNamed:[NSString stringWithFormat:@"book_star_%@.png", bookItem.bookStar]];
    //currentContent.text = bookItem.bookContentInfo;
    if([bookItem bookContentInfo] != nil && ![[bookItem bookContentInfo] isEqualToString:@""]){
        currentContent.text = [[bookItem bookContentInfo] stringByReplacingOccurrencesOfRegex:@"&#[a-z]{2,4};" withString:@""];
    }else{
        currentContent.text = @"";
    }
    
    //如果图片在本地，则直接显示，否则从服务端下载图片再显示
    if([[NSFileManager defaultManager] fileExistsAtPath:[kDocumentFolder stringByAppendingPathComponent:[bookItem bookIconSmall]]]
       ){
        bookFaceView.image = [UIImage imageWithContentsOfFile:[kDocumentFolder stringByAppendingPathComponent:[bookItem bookIconSmall]]];
    }
    /*
    //异步显示图片
    if([CommonUtil isConnected]){
        NSOperationQueue *queue = [NSOperationQueue new];
        [queue setMaxConcurrentOperationCount:1];
        NSInvocationOperation *operation = [[NSInvocationOperation alloc] 
                                            initWithTarget:self
                                            selector:@selector(loadImage:) 
                                            object:[NSString stringWithFormat:@"%@%@%@", kServerURL, kFilei240, [bookItem bookIconSmall]]];
        [queue addOperation:operation]; 
        [operation release];
    }*/
    
    //NSLog(@"bookExt1:%@", [bookItem bookExt1]);
    if([bookItem bookExt1] != nil && [[bookItem bookExt1] isEqualToString:@"1"]){
        BookItem *tmpBookItem = [[BookItem alloc] init];
                                 
        //插入到本地数据库
        DBUtil *db = [[DBUtil alloc] init];
        [db openDB];
        [db getBookDetailData:tmpBookItem bookId:bookId];
        [db closeDB];
        [db release];
        
        //更新标签数据
        if([tmpBookItem bookSeries] != nil && ![[tmpBookItem bookSeries] isEqualToString:@""]) {
            bookCategory.text = [NSString stringWithFormat:@"%@：%@", [bookItem bookCategory1], [tmpBookItem bookSeries]];
        }
        bookPressTime.text = [tmpBookItem bookPressTime];
        bookPress.text = [tmpBookItem bookPress];
        bookWords.text = [tmpBookItem bookWords];
        bookLanguage.text = [tmpBookItem bookLanguage];
        //currentContent.text = [tmpBookItem bookContentInfo];
        if([tmpBookItem bookContentInfo] != nil && ![[tmpBookItem bookContentInfo] isEqualToString:@""]){
            currentContent.text = [[tmpBookItem bookContentInfo] stringByReplacingOccurrencesOfRegex:@"&#[a-z]{2,4};" withString:@""];
        }else{
            currentContent.text = @"";
        }
        
        bookItem.bookContentInfo = tmpBookItem.bookContentInfo;
        bookItem.bookEditorInfo = tmpBookItem.bookEditorInfo;
        bookItem.bookAuthorInfo = tmpBookItem.bookAuthorInfo;
        bookItem.bookCatalog = tmpBookItem.bookCatalog;
        bookItem.bookContentInfo = tmpBookItem.bookContentInfo;
        bookItem.bookFreeContent = tmpBookItem.bookFreeContent;
        [waitingView stopAnimating];
    }else{
        if([CommonUtil isConnected]){
            //去服务端检查新书，如果有则返回最新的50本图书
            CommonDetailWebServices *ws = [[CommonDetailWebServices alloc] init];
            [ws setDelegate:self];
            [ws getWebServicesData:bookId page:@""];
        }
    }
    
    if([[bookItem bookDownFlag] isEqualToString:@"1"]){
        /*
         [buyButton setTitle:@"阅读" forState:UIControlStateNormal];
         [buyButton removeTarget:self action:@selector(buyButtonClick:) forControlEvents:UIControlEventTouchUpInside];
         [buyButton addTarget:self action:@selector(readButtonClick:) forControlEvents:UIControlEventTouchUpInside];
         */
        [buyButton setTitle:@"已下载" forState:UIControlStateNormal];
        buyButton.enabled = NO;
        [buyButton removeTarget:self action:@selector(downClick:) forControlEvents:UIControlEventTouchUpInside];
        
    }else if([[bookItem bookBuyFlag] isEqualToString:@"1"]){
        [buyButton setTitle:@"下载" forState:UIControlStateNormal];
    }else{
        if([[bookItem bookPrice] isEqualToString:@"0"]){
            [buyButton setTitle:@"免费" forState:UIControlStateNormal];
        }else{
            /*[buyButton setTitle:[NSString stringWithFormat:@"￥%1.2f", [[bookItem bookPrice] intValue]*6.0] forState:UIControlStateNormal];
             */
            NSLocale* curentLocale = [NSLocale currentLocale];
            //NSLog(@"curentLocale.description=%@", curentLocale.localeIdentifier);
            if([curentLocale.localeIdentifier isEqualToString:@"zh_CN"]){
                [buyButton setTitle:[NSString stringWithFormat:@"￥%1.2f", [[bookItem bookPrice] intValue]*6.0] forState:UIControlStateNormal];
            }else{
                [buyButton setTitle:[NSString stringWithFormat:@"$%1.2f", [[bookItem bookPrice] intValue]*1.0 - 0.01] forState:UIControlStateNormal];
            }
            //priceLabel.text = [NSString stringWithFormat:@"$%1.2f", [[bookItem bookPrice] intValue] - 0.01];
        }
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
	return YES;
}

-(IBAction)hiddenDetail:(id)sender {
    [self dismissModalViewControllerAnimated:YES];
}

-(IBAction)changeContent:(id)sender{
    [currentButton setBackgroundImage:[UIImage imageNamed:@"detail_button_bg2.png"] forState:UIControlStateNormal];
    currentButton = (UIButton *)sender;
    [currentButton setBackgroundImage:[UIImage imageNamed:@"detail_button_bg.png"] forState:UIControlStateNormal];
    int tag = [(UIButton *)sender tag];
    if(tag == 1){
        //currentContent.text = [bookItem bookContentInfo];
        if([bookItem bookContentInfo] != nil && ![[bookItem bookContentInfo] isEqualToString:@""]){
        currentContent.text = [[bookItem bookContentInfo] stringByReplacingOccurrencesOfRegex:@"&#[a-z]{2,4};" withString:@""];
        }else{
            currentContent.text = @"";
        }
    }else if(tag == 2){
        //currentContent.text = [bookItem bookEditorInfo];
        if([bookItem bookEditorInfo] != nil && ![[bookItem bookEditorInfo] isEqualToString:@""]){
            currentContent.text = [[bookItem bookEditorInfo] stringByReplacingOccurrencesOfRegex:@"&#[a-z]{2,4};" withString:@""];
        }else{
            currentContent.text = @"";
        }
    }else if(tag == 3){
        //currentContent.text = [bookItem bookAuthorInfo];
        if([bookItem bookAuthorInfo] != nil && ![[bookItem bookAuthorInfo] isEqualToString:@""]){
            currentContent.text = [[bookItem bookAuthorInfo] stringByReplacingOccurrencesOfRegex:@"&#[a-z]{2,4};" withString:@""];
        }else{
            currentContent.text = @"";
        }
    }else if(tag == 4){
        //currentContent.text = [bookItem bookCatalog];
        if([bookItem bookCatalog] != nil && ![[bookItem bookCatalog] isEqualToString:@""]){
            currentContent.text = [[bookItem bookCatalog] stringByReplacingOccurrencesOfRegex:@"&#[a-z]{2,4};" withString:@""];
        }else{
            currentContent.text = @"";
        }
    }else if(tag == 5){
        //currentContent.text = [bookItem bookContentInfo];
    }
}

-(IBAction)favorClick:(id)sender{
    DBUtil *db = [[DBUtil alloc] init];
    [db openDB];
    [db updateBook:@"favorite" key:bookId value:bookId];
    [db closeDB];
    [db release];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"收藏成功" message:@"" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil, nil];
    [alert show];
    [alert release];
}

//将返回的数据写入本地数据表
- (void)onCommonDetailWebServicesOver:(NSDictionary *) dic {
    //NSLog(@"onCommonWebServicesOver");
    NSMutableArray *tmpData = [[NSMutableArray alloc] initWithCapacity:2];
    
    if([dic objectForKey:@"dataTable"] != nil) {
        tmpData = [dic objectForKey:@"dataTable"];
        //NSLog(@"tmpData:%d", [tmpData count]);
        if([tmpData count] > 0){
            BookItem *tmpBookItem = [tmpData objectAtIndex:0];
            
            //插入到本地数据库
            DBUtil *db = [[DBUtil alloc] init];
            [db openDB];
            [db updateBookData:tmpBookItem];
            [db closeDB];
            [db release];
            
            //更新标签数据
            if([tmpBookItem bookSeries] != nil && ![[tmpBookItem bookSeries] isEqualToString:@""]) {
                bookCategory.text = [NSString stringWithFormat:@"%@：%@", [bookItem bookCategory1], [tmpBookItem bookSeries]];
            }
            bookPressTime.text = [tmpBookItem bookPressTime];
            bookPress.text = [tmpBookItem bookPress];
            bookWords.text = [tmpBookItem bookWords];
            bookLanguage.text = [tmpBookItem bookLanguage];
            //currentContent.text = [tmpBookItem bookContentInfo];
            if([tmpBookItem bookContentInfo] != nil && ![[tmpBookItem bookContentInfo] isEqualToString:@""]){
                currentContent.text = [[tmpBookItem bookContentInfo] stringByReplacingOccurrencesOfRegex:@"&#[a-z]{2,4};" withString:@""];
            }else{
                currentContent.text = @"";
            }
            
            bookItem.bookContentInfo = tmpBookItem.bookContentInfo;
            bookItem.bookEditorInfo = tmpBookItem.bookEditorInfo;
            bookItem.bookAuthorInfo = tmpBookItem.bookAuthorInfo;
            bookItem.bookCatalog = tmpBookItem.bookCatalog;
            bookItem.bookContentInfo = tmpBookItem.bookContentInfo;
            bookItem.bookFreeContent = tmpBookItem.bookFreeContent;
            
        }
    }
    [tmpData release];
}

- (void)onCommonDetailWebServicesFaild:(NSString *)error {
    //NSLog(@"onCommonWebServicesFaild");
}

-(void)loadImage:(NSString *)url {
    //NSLog(@"url000:%@", url);
    NSData* imageData = [[NSData alloc]initWithContentsOfURL:
                         [NSURL URLWithString:url]];
    bookFaceView.image = [[UIImage alloc] initWithData:imageData];
    [imageData release];
}


-(IBAction)buyButtonClick:(id)sender {
    if(![CommonUtil isConnected]) {
        UIAlertView *alert = [[UIAlertView alloc] 
                              initWithTitle:@"无法连接到服务器" 
                              message:@"请检查设备是否已打开3G网络或者通过Wi-Fi接入互联网。"  
                              delegate:self cancelButtonTitle:@"确定" 
                              otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        return;
    }
    
    HubuAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    if(delegate.hubuViewController.isDownloading){
        UIAlertView *alert = [[UIAlertView alloc] 
                              initWithTitle:@"请等待..." 
                              message:@"已经有图书正在下载，请下载完后再下载其他图书。"  
                              delegate:self cancelButtonTitle:@"确定" 
                              otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        return;
    }
    
    UIButton *b = (UIButton *)sender;
    CGPoint p = CGPointMake(160, 240);
    delegate.hubuViewController.downloadingButtonTitle = [buyButton titleLabel].text;
    delegate.hubuViewController.downloadButtonTag = [[bookItem pkId] intValue] + buyBtnTagBegin;
    [delegate.hubuViewController downloadStart:p bookItem:bookItem];
    
    if([bookItem.bookPrice isEqualToString:@"0"]){
        //设置正在下载全局变量
        delegate.hubuViewController.isDownloading = TRUE;
        [buyButton setTitle:@"下载中" forState:UIControlStateNormal];
        [buyButton removeTarget:self action:@selector(buyButtonClick:) forControlEvents:UIControlStateNormal];
        [buyButton setEnabled:NO];
        
        [delegate.hubuViewController downloadStartNow];
    }else{
        [self requestProductData];
    }
    
    /*下载
     downloadManager=[[DownloadManager alloc] init];
     downloadManager.title= titleLabel.text;
     downloadManager.fileURL=[NSURL URLWithString:[NSString stringWithFormat: @"%@files/this_is_source_folder/pad/%@_4.pdf", kServerURL, [localBookItem bookId]]];
     //downloadManager.fileName=[kDocumentFolder stringByAppendingPathComponent:[localBookItem book4PadResource]];
     NSString *fileName = [[localBookItem book4PadResource] stringByDeletingPathExtension];
     fileName = [NSString stringWithFormat:@"%@.pdf",fileName];
     
     downloadManager.fileName=[kDocumentFolder stringByAppendingPathComponent:fileName];
     downloadManager.delegate = self;
     [downloadManager start];
     */
}

-(IBAction)downClick:(id)sender {
    HubuAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    [delegate.hubuViewController downloadStart:CGPointMake(512, 384) bookItem:bookItem];
    [delegate.hubuViewController downloadStartNow];
}



#pragma mark -
#pragma mark SotoreKit method
- (void) requestProductData {
	if ([SKPaymentQueue canMakePayments]) {	
        SKProductsRequest *request= [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:[[bookItem bookCode] stringByReplacingOccurrencesOfString:@".a01." withString:@".a02."]]];
		//SKProductsRequest *request= [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:@"com.cjcb.a01.b1000"]];
        //NSLog(@"bookCode:%@", [localBookItem bookCode]);
		request.delegate = self;
		[request start];
	}else{		
		UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:@"警告" 
                                                            message:@"苹果应用商店（App Store）不可用。"
														   delegate:nil 
                                                  cancelButtonTitle:@"确定" otherButtonTitles:nil];
		
		[alerView show];
		[alerView release];
		//[m_buyButton setEnabled:YES];
	}
}

#pragma mark request delegate
//收到产品的消息
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
	NSArray *myProduct = response.products;
	//NSLog(@"the count of products is %d", [myProduct count]);
    /*
     NSArray *products = response.products;
     SKProduct *proUpgradeProduct = [products count] == 1 ? [[products firstObject] retain] : nil;
     if (proUpgradeProduct)
     {
     NSLog(@"Product title: %@" , proUpgradeProduct.localizedTitle);
     NSLog(@"Product description: %@" , proUpgradeProduct.localizedDescription);
     NSLog(@"Product price: %@" , proUpgradeProduct.price);
     NSLog(@"Product id: %@" , proUpgradeProduct.productIdentifier);
     }
     
     for (NSString *invalidProductId in response.invalidProductIdentifiers)
     {
     NSLog(@"Invalid product id: %@" , invalidProductId);
     }
     */
    // finally release the reqest we alloc/init’ed in requestProUpgradeProductData
    //[productsRequest release];
	
	BOOL bIsExist = NO;
	for(SKProduct *product in myProduct){
		SKPayment *payment = [SKPayment paymentWithProductIdentifier:[product productIdentifier]];
		[[SKPaymentQueue defaultQueue] addPayment:payment];
		[request release];
	    //启动时间检测
		bIsExist = YES;
	}
	
	if (!bIsExist) {
		UIAlertView *alertView =  [[UIAlertView alloc] initWithTitle:@"提示" 
                                                             message:@"该商品在等待苹果应用商店（App Store)审核，审核后即可购买"
                                                            delegate:nil 
                                                   cancelButtonTitle:@"关闭"
                                                   otherButtonTitles:nil];
		[alertView show];
		[alertView release];
        
		//[m_buyButton setEnabled:YES];
	}
}


- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
	UIAlertView *alertView =  [[UIAlertView alloc] initWithTitle:@"错误" message:[error localizedDescription]
                                                        delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
	
	[alertView show];
	[alertView release];
}

@end
